package main

import (
	"flag"
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/fiorix/go-eventsocket/eventsocket"
	"strconv"
	"time"
)

// @title       `gf-demo`示例服务API
// @version     1.0
// @description `GoFrame`基础开发框架示例服务API接口文档。
// @schemes     http
var(
	fsHost    = flag.String("fsHost", g.Cfg().GetString("fs.inbound.host"), "Freeswitch hostname. Default: localhost")
	fsPort    = flag.Uint("fsPort", g.Cfg().GetUint("fs.inbound.port"), "Freeswitch port. Default: 8021")
	password  = flag.String("pass", g.Cfg().GetString("fs.inbound.password"), "Freeswitch password. Default: ClueCon")
	pcs = flag.Uint("pcs", g.Cfg().GetUint("call.pcs"), "每秒发起呼叫的数量")
	startUser = flag.String("startUser", g.Cfg().GetString("call.start_user"), "开始分机")
	endUser = flag.String("endUser", g.Cfg().GetString("call.end_user"), "截止分机")
	startDest = flag.String("startDest", g.Cfg().GetString("call.start_dest"), "开始被叫号码")
	endDest = flag.String("endDest", g.Cfg().GetString("call.end_dest"), "截止被叫号码")
	//uuidMap   = _UUIDMap{Mutex: &sync.Mutex{}, data: map[string]string{}}
	//confMap	  = _CONFMap{Mutex: &sync.Mutex{}, data: map[string]string{}}
	//Con       *fs.Connection
	//Err       error
)

// Connection 连接
//type Connection struct {
//	Connection 	*eventsocket.Connection
//	Err        	chan error
//	Record     	chan Record
//	ConfRecord  chan ConfRecord
//	EVENT		chan Event
//}

// CreateConnection 创建esl连接（inbound）...
func CreateConnection() (*eventsocket.Connection, error) {
	esc, err := eventsocket.Dial(fmt.Sprintf("%v:%v", *fsHost, *fsPort), *password)
	if err != nil {
		return nil, err
	}
	return esc, nil
}

func CountPCS(p uint) float64{
	t := float64(p)
	i := 1/t
	value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", i), 64)
	return value
}

func main() {
	//g.Server().Run()
	fmt.Println("host = ", *fsHost)
	conn, err := CreateConnection()
	if err != nil {
		fmt.Println("FreeSWITCH Esl Connection Err:", err.Error())
	}
	sleepT := CountPCS(*pcs) * 1000
	su, _ := strconv.Atoi(*startUser)
	eu, _ := strconv.Atoi(*endUser)

	fmt.Println("sleep time: ", sleepT)
	sd, _ := strconv.Atoi(*startDest)
	ed, _ := strconv.Atoi(*endDest)
	count := 0
	for i:=su; i<=eu; i++ {
			if sd > ed {
				break
			}
			cmd := "bgapi originate user/" + strconv.Itoa(i) + " " + strconv.Itoa(sd) + " XML default"
			//cmd := "originate user/" + strconv.Itoa(i) + "bridge(XML default 8888)"
			fmt.Println(cmd)
			conn.Send(cmd)
			time.Sleep(time.Duration(sleepT) * time.Millisecond)
			sd++
			count++
	}
	fmt.Println("已发出呼叫：", count)
}
